#!/usr/bin/python
# -*- coding: utf-8 -*-

#from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import Group
from django.http import Http404, HttpResponseRedirect 

def check_role(role=None, next=None):
    '''
    only check one of role
    @param role:
    @param next:
    '''
    def _check_permission(request, role):
        if Group.objects.filter(name=role): #@UndefinedVariable
            perms_to_check = Group.objects.get(name=role).permissions.all() #@UndefinedVariable
            perms = []
            for group in request.user.groups.all():
                perms.extend(group.permissions.all())
            for p in perms_to_check:
                if p not in perms:
                    return False
            else:
                return True
        else:
            raise Http404

    def _check_role(view_func):
        def _wrapper(request, *args, **kwargs):
            if request.user.is_anonymous():
                return HttpResponseRedirect('/accounts/login/')
            #如果没有role参数，就默认为不设任何限制        
            if role==None:
                return view_func(request, *args, **kwargs)
            else:
                role_check=_check_permission(request, role)
                if role_check:
                    return view_func(request, *args, **kwargs)
                else:
                    return HttpResponseRedirect('/error_permission/')
        return _wrapper
    return _check_role

def check_roles(roles=None):
    '''
    it can be check a lot of roles
    '''
    def _check_permission(request, role):
        if Group.objects.filter(name=role): #@UndefinedVariable
            perms_to_check = Group.objects.get(name=role).permissions.all() #@UndefinedVariable
            perms = []
            for group in request.user.groups.all():
                perms.extend(group.permissions.all())
            for p in perms_to_check:
                if p not in perms:
                    return False
            else:
                return True
        else:
            raise Http404

    def _check_role(view_func):
        def _wrapper(request, *args, **kwargs):
            if request.user.is_anonymous():
                return HttpResponseRedirect('/accounts/login/')
            #如果没有roles参数，就默认为不设任何限制        
            if roles==None:
                return view_func(request, *args, **kwargs)
            else:
                for role in roles:
                    role_check=_check_permission(request, role)
                    if role_check:
                        return view_func(request, *args, **kwargs)
                    else:
                        # not valid role , check next
                        pass
                # all roles not match, return Error Permission
                return HttpResponseRedirect('/error_permission/')
        return _wrapper
    return _check_role

